window.onload = function() {
	var list = document.getElementById("list"),
		item = list.getElementsByTagName("li"),
		itemLen = item.length,
		itemPos = [],
		flag = true,
		minZindex = 10;

	init();

	//初始化
	function init() {
		//保存原始位置
		for(var i = 0; i < itemLen; i++) {
			itemPos[i] = {
				"left": item[i].offsetLeft,
				"top": item[i].offsetTop
			};
		}
		//改变布局方式
		for(i = 0; i < itemLen; i++) {
			item[i].style.left = itemPos[i].left + "px";
			item[i].style.top = itemPos[i].top + "px";
			item[i].style.position = "absolute";
			item[i].style.margin = 0;
			item[i].index = i;
			//如果小于10个则用遍历方式添加拖拽
			if(itemLen < 10) {
				setDrag(item[i]);
			}
		}
		//如果大于等于10个则用事件委托方式添加拖拽
		if(itemLen >= 10) {
			setDrag(list, true);
		}
	}
	//添加拖拽
	function setDrag(obj, handleby) {
		obj.onmousedown = function(event) {
			var e = event || window.event,
				target = e.target || e.srcElement;
			//事件委托
			if(handleby && handleby == true) {
				if(target.nodeName === item[0].nodeName) {
					handler(target, e);
				};
			} else {
				handler(obj, e);
			}
		}
	}
	//拖拽处理程序
	function handler(target, e) {
		var ltIE9 = checkLtIE9(),
			disX = getPagePos(e).x - target.offsetLeft,
			disY = getPagePos(e).y - target.offsetTop;
		//防止图片处于被选中状态
		window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
		//被拖拽的对象处于最顶层
		target.style.zIndex = minZindex++;

		document.onmousemove = function(event) {
			var e = event || window.event;
			//被拖拽的对象跟随鼠标
			target.style.left = getPagePos(e).x - disX + "px";
			target.style.top = getPagePos(e).y - disY + "px";
			//清空样式
			for(var i = 0; i < itemLen; i++) {
				item[i].className = "";
			}

			var near = findNearest(target);

			if(near) {
				//最近的对象设置样式
				near.className = "active";
			}
		};

		document.onmouseup = function() {
			document.onmousemove = null;
			document.onmouseup = null;

			if(ltIE9) {
				target.releaseCapture();
			}

			var near = findNearest(target);

			if(near) {
				near.className = "";
				near.style.zIndex = minZindex++;
				target.style.zIndex = minZindex++;

				animate(near, itemPos[target.index]);
				animate(target, itemPos[near.index]);

				var tmp = target.index;

				target.index = near.index;
				near.index = tmp;
				//另一种互换index的方案，不借用第三者
				/*obj.index += near.index;
				near.index = obj.index - near.index;
				obj.index -= near.index;*/
			} else {
				//没有靠近的对象则返回原来位置
				animate(target, itemPos[target.index]);
			}
		};

		ltIE9 ? target.setCapture() : preventDefault(e);
		//防止动画未停止，又被拖拽出现抖动
		clearInterval(target.timer);
	}
	//碰撞检测
	function cdTest(obj1, obj2) {
		var t1 = obj1.offsetTop,
			r1 = obj1.offsetLeft + obj1.offsetWidth,
			b1 = obj1.offsetTop + obj1.offsetHeight,
			l1 = obj1.offsetLeft,

			t2 = obj2.offsetTop,
			r2 = obj2.offsetLeft + obj1.offsetWidth,
			b2 = obj2.offsetTop + obj1.offsetHeight,
			l2 = obj2.offsetLeft;

		if(t1 > b2 || r1 < l2 || b1 < t2 || l1 > r2) {
			return false;
		}

		return true;
	}
	//勾股定理计算距离
	function getDis(obj1, obj2) {
		var x = obj2.offsetLeft - obj1.offsetLeft,
			y = obj2.offsetTop - obj1.offsetTop;

		return Math.sqrt(x * x + y * y);
	}
	//查找距离最近的对象
	function findNearest(obj) {
		var min = 999999,//足够大的数即可
			minIndex = -1;

		for(var i = 0; i < itemLen; i++) {
			//如果是当前对象则跳出本次循环
			if(obj === item[i]) continue;

			if(cdTest(obj, item[i])) {
				var dis = getDis(obj, item[i]);
				if(dis < min) {
					min = dis;
					minIndex = i;
				}
			}
		}

		if(minIndex === -1) {
			return null;
		}
		return item[minIndex];
	}
	//pageX/pageY兼容方案
	function getPagePos(e) {
		var pos = {
			"x": 0,
			"y": 0
		};

		if(e.pageX) {
			pos.x = e.pageX;
			pos.y = e.pageY;
		} else {
			pos.x = e.clientX + (document && document.documentElement.scrollLeft || document.body && document.body.scrollLeft || 0) - (document && document.documentElement.clientLeft || document.body && document.body.clientLeft || 0);
			pos.y = e.clientY + (document && document.documentElement.scrollTop || document.body && document.body.scrollTop || 0) - (document && document.documentElement.clientTop || document.body && document.body.clientTop || 0);
		}

		return pos;
	}
	//获取计算后的样式
	function getStyle(obj, attr) {
		if(obj.currentStyle) {
			return obj.currentStyle[attr];
		}
		return getComputedStyle(obj, false)[attr];

	}
	//动画程序
	function animate(obj, json, fn) {
		clearInterval(obj.timer);
		obj.timer = setInterval(function() {
			var bool = true;

			for(var attr in json) {
				var current = (attr == "opacity") ? Math.round(getStyle(obj, attr) * 100) : (parseInt(getStyle(obj, attr)) || 0),
					target = json[attr][0] || json[attr],
					steps = json[attr][1] || 10,
					speed = (target - current) / steps;

				speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
				current = current + speed;

				if(attr == 'opacity') {
					obj.style.filter = 'alpha(opacity:' + current + ')';
					obj.style[attr] = current / 100;

				} else {
					obj.style[attr] = current + 'px';
				}
				//所有动画结束
				if(target !== current) {
					bool = false;
				}
			}

			if(bool) {
				clearInterval(obj.timer);
				if(fn) {
					fn();
				}
			}
		}, 1000 / 60);
	}
	//检测IE版本是否小于9
	function checkLtIE9() {
		var userAgent = navigator.userAgent;

		return userAgent.indexOf("MSIE") > 0 && (
			userAgent.indexOf("MSIE 6.0") > 0 ||
			userAgent.indexOf("MSIE 7.0") > 0 ||
			userAgent.indexOf("MSIE 8.0") > 0);
	}
	//组织浏览器默认行为
	function preventDefault(event) {
		if(event.preventDefault) {
			event.preventDefault();
		} else {
			event.returnValue = false;
		}
	}
};